package com.zhan.drugStore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhan.drugStore.bean.entity.Hobby;
import com.zhan.drugStore.bean.entity.User;
import com.zhan.drugStore.bean.entity.UserHobby;
import com.zhan.drugStore.bean.form.UserForm;
import com.zhan.drugStore.bean.form.UserSearch;
import com.zhan.drugStore.bean.vo.UserVO;
import com.zhan.drugStore.dao.UserMapper;
import com.zhan.drugStore.service.HobbyService;
import com.zhan.drugStore.service.UserHobbyService;
import com.zhan.drugStore.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhan.drugStore.util.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zy
 * @since 2024-07-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserHobbyService userHobbyService;

    @Override
    public List<UserVO> userList(UserSearch form) {
        List<UserVO> userVOList = baseMapper.getUserVOList(new UserForm());
        return CollectionUtils.isEmpty(userVOList)? new ArrayList<>():userVOList;
    }

    @Override
    public List<UserVO> getMatchUserList(Long id) {
        UserVO userVO = baseMapper.getUserVOById(id);
        //查询匹配用户
        UserForm userForm = new UserForm();
        userForm.setAgeMax(userVO.getAge() + 3);
        userForm.setAgeMin(userVO.getAge() - 3);
        userForm.setGender(userVO.getMatchPreference());
        if(Objects.equals(userVO.getAdjustmentPreference(), User.NOT_ACCEPT_ANOTHER_CITY)){
            userForm.setCity(userVO.getCity());
        }
        List<UserVO> matchUserList = baseMapper.getUserVOList(userForm);
        return  sortMatchUserListByCommonHobbies(userVO, matchUserList);
    }

    @Override
    public void addOrUpdate(UserForm userForm) {
        this.saveOrUpdate(userForm);
        //先删除在新增
        userHobbyService.deleteUserHobby(userForm.getId());
        List<Hobby> hobbyList = userForm.getHobbyList();
        if(!CollectionUtils.isEmpty(hobbyList)){
            List<UserHobby> userHobbies = new ArrayList<>();
            for (Hobby hobby : hobbyList) {
                UserHobby userHobby = new UserHobby();
                userHobby.setUserId(userForm.getId());
                userHobby.setHobbyId(hobby.getId());
                userHobbies.add(userHobby);
            }
            userHobbyService.saveBatch(userHobbies);
        }
    }

    /**
     * 按照共同爱好数量对满足要求的用户集合排序
     * @param userVO 需要匹配的用户
     * @param matchUserList 满足要求的用户集合
     * @return 满足要求的用户集合排序
     */
    private List<UserVO> sortMatchUserListByCommonHobbies(UserVO userVO, List<UserVO> matchUserList) {
        if (userVO == null || CollectionUtils.isEmpty(matchUserList)) {
            return Collections.emptyList();
        }

        // 收集共同爱好数量和对应的用户
        Map<Integer, List<UserVO>> commonHobbiesCountMap = new LinkedHashMap<>();

        for (UserVO matchUser : matchUserList) {
            // 计算两个用户的共同爱好数量
            Set<Hobby> commonHobbies = new HashSet<>(userVO.getHobbyList());
            commonHobbies.retainAll(matchUser.getHobbyList());

            int commonHobbiesCount = commonHobbies.size();

            // 将用户放入对应共同爱好数量的列表中
            commonHobbiesCountMap.computeIfAbsent(commonHobbiesCount, k -> new ArrayList<>()).add(matchUser);
        }

        // 按照共同爱好数量降序排序
        List<UserVO> sortedMatchUserList = new ArrayList<>();
        commonHobbiesCountMap.entrySet().stream()
                .sorted(Map.Entry.<Integer, List<UserVO>>comparingByKey().reversed())
                .forEach(entry -> sortedMatchUserList.addAll(entry.getValue()));

        return sortedMatchUserList;
    }
}
